//
//  GAKKIUtils.m
//  Interview
//
//  Created by fh on 2021/3/3.
//

#import "GAKKIUtils.h"
#import "GAKKIKeyChainStore.h"
#import <AdSupport/AdSupport.h>

static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@interface GAKKIUtils ()

@end

@implementation GAKKIUtils

/// 字符串base64编码
/// @param str base64编码字符串
+ (NSString *)base64encode:(NSString *)str {
    if ([str length] == 0) {
        return @"";
    }
    const char *source = [str UTF8String];
    unsigned long strlength  = strlen(source);
    char *characters = malloc(((strlength + 2) / 3) * 4);
    if (characters == NULL) {
         return nil;
    }
    NSUInteger length = 0;
    NSUInteger i = 0;
    while (i < strlength) {
        char buffer[3] = {0,0,0};
        short bufferLength = 0;
        while (bufferLength < 3 && i < strlength)
            buffer[bufferLength++] = source[i++];
        characters[length++] = base64[(buffer[0] & 0xFC) >> 2];
        characters[length++] = base64[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
        if (bufferLength > 1)
            characters[length++] = base64[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
        else characters[length++] = '=';
        if (bufferLength > 2)
            characters[length++] = base64[buffer[2] & 0x3F];
        else characters[length++] = '=';
    }
    NSString *g = [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES] ;
    return g;
}

/// 获取唯一UUID
+ (NSString *)getUniqueStrByUUID {
    NSString *key = [NSString stringWithFormat:@"%@.usernamepassword",[NSBundle mainBundle].bundleIdentifier];
    // 这个key的前缀最好是你的BundleID
    NSString *strUUID = (NSString*)[GAKKIKeyChainStore load:key];
    // 首次执行该方法时，uuid为空
    if([strUUID isEqualToString:@""]|| !strUUID) {
        // 获取UUID 这个是要引入<AdSupport/AdSupport.h>的
        strUUID = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        if(strUUID.length ==0 || [strUUID isEqualToString:@"00000000-0000-0000-0000-000000000000"]) {
            //生成一个uuid的方法
            CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
            strUUID = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault,uuidRef));
            CFRelease(uuidRef);
        }
        // 将该uuid保存到keychain
        [GAKKIKeyChainStore save:key data:strUUID];
    }
    return strUUID;
    
    //    // 随机UUID
    //    return [[NSUUID UUID] UUIDString];
    //    // 随机UUID
    //    CFUUIDRef uuidObj = CFUUIDCreate(nil);
    //    NSString *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    //    CFRelease(uuidObj);
    //    return uuidString ;
}

@end
